package com.tzpay.tzpay.db;

import java.util.ArrayList;

import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.tzpay.tzpay.common.StaticVars;

/**
 * Created by chenfeiyue on 16/4/7.
 */
public class TzPayContentProvider extends ContentProvider {
    private static final int ID_MUTIMEDIA_INFO = 1;
    private TzPayDBHelper dbHelper;
    private UriMatcher matcher;

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int result = 0;
        switch (matcher.match(uri)) {
            case ID_MUTIMEDIA_INFO:
                result = deleteOrderInfoInfo(selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        return result;
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ContentProviderResult[] applyBatch(
            ArrayList<ContentProviderOperation> operations)
            throws OperationApplicationException {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentProviderResult[] results = super.applyBatch(operations);
            db.setTransactionSuccessful();
            return results;
        } finally {
            db.endTransaction();
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        Uri result = null;
        long ret = 0;

        switch (matcher.match(uri)) {
            case ID_MUTIMEDIA_INFO:
                ret = insertOrderInfo(values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        if (ret > 0) {
            result = ContentUris.withAppendedId(uri, ret);
            getContext().getContentResolver().notifyChange(result, null);
        }
        return result;
    }

    @Override
    public boolean onCreate() {
        dbHelper = new TzPayDBHelper(getContext());

        matcher = new UriMatcher(UriMatcher.NO_MATCH);

        matcher.addURI(StaticVars.URI.AUTHORITY,
                StaticVars.Table.ORDER_INFO, ID_MUTIMEDIA_INFO);
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        Cursor cursor = null;
        switch (matcher.match(uri)) {
            case ID_MUTIMEDIA_INFO:
                cursor = queryOrderInfo(projection, selection,
                        selectionArgs, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int result = 0;
        switch (matcher.match(uri)) {
            case ID_MUTIMEDIA_INFO:
                result = updateeOrderInfoInfo(values, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        return result;
    }

    /**
     * 判断容量是否超过最大值，若超过，则删除一部分
     * 删除上传成功的数据
     *
     * @return 操作完，表里的记录数
     */
    private static int judge(SQLiteDatabase db, String table, int max, int delCount,
                             int currCount) {
        if (currCount > max) {
            String sql = "delete from " + table + " where " + StaticVars.Column._ID + " in"
                    + " (select " + StaticVars.Column._ID + " from " + table /*+ "where " + StaticVars.Column.UPLOAD_FLAG
                    + " = " + OrderInfo.UPLOAD_SUCCESS*/
                    + " order by " + StaticVars.Column._ID + " asc limit "
                    + delCount + ") ";
            db.execSQL(sql);
            currCount -= delCount;
        }
        return currCount;
    }

    private long insertOrderInfo(ContentValues values) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long result = db.insert(StaticVars.Table.ORDER_INFO, null, values);

        StaticVars.ORDERINFO_CURR_COUNT++;
        StaticVars.ORDERINFO_CURR_COUNT = judge(db, StaticVars.Table.ORDER_INFO,
                StaticVars.ORDERINFO_MAX_COUNT, StaticVars.ORDERINFO_DELETE_COUNT,
                StaticVars.ORDERINFO_CURR_COUNT);
        return result;
    }

    private Cursor queryOrderInfo(String[] columns, String selection,
                                  String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query(StaticVars.Table.ORDER_INFO, columns,
                selection, selectionArgs, null, null, sortOrder);
    }

    private int deleteOrderInfoInfo(String selection, String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.delete(StaticVars.Table.ORDER_INFO, selection,
                selectionArgs);
    }

    private int updateeOrderInfoInfo(ContentValues values, String selection,
                                     String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.update(StaticVars.Table.ORDER_INFO, values, selection,
                selectionArgs);
    }

    public boolean updateOrInsertOrderInfoInfo(Context context, ContentValues values, String selection,
                                               String[] selectionArgs) {
        Cursor cursor = null;
        ContentResolver contentResolver = context.getApplicationContext().getContentResolver();
        try {
            // null 返回所有列
            cursor = contentResolver.query(StaticVars.URI.ORDER_INFO, null, selection, selectionArgs, null);
            if (cursor != null && cursor.getCount() > 0) {
                // update
                contentResolver.update(StaticVars.URI.ORDER_INFO, values, selection, selectionArgs);
                return true;
            } else {
                contentResolver.insert(StaticVars.URI.ORDER_INFO, values);
                return true;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public void initDB(Context context) {
        Cursor cursor;
        cursor = context.getApplicationContext().getContentResolver().query(StaticVars.URI.ORDER_INFO,
                null,
                null,
                null,
                null);
        if (cursor != null) {
            StaticVars.ORDERINFO_CURR_COUNT = cursor.getCount();
            cursor.close();
        }
    }

}
